from django import forms
import re
from .models import User
from django.db.models import Q
from django.contrib.auth import login


class LoginForm(forms.Form):
    username = forms.CharField()
    password = forms.CharField(max_length=20, required=True, min_length=5, strip=True, error_messages={
        "max_length": "密碼格式錯誤",
        "min_length": "密碼格式錯誤",
        "required": "密碼不能為空"
    })

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop("request")
        super().__init__(*args, **kwargs)

    def clean_username(self):
        username = self.cleaned_data.get("username")
        if not username:
            raise forms.ValidationError("用户名不能为空")
        if not re.match(r"^\d{8,20}$", username):
            raise forms.ValidationError("用户名格式错误")
        return username

    def clean(self):
        cleaned_data = super().clean();
        username = cleaned_data.get("username")
        password = cleaned_data.get("password")
        remember = cleaned_data.get("remember")
        # 判断是否是用户名还是手机号
        users = User.objects.filter(Q(username=username) | Q(mobile=username))
        if users:
            user = users.first()
            if user.check_password(password):
                if remember:
                    self.request.session.set_expiry(60*60*24*30)
                login(self.request, user)
            else:
                raise forms.ValidationError("密码错误")
        else:
            raise forms.ValidationError("用户名不存在")
        return cleaned_data




    # 自定義過濾函數，clean_field_name，如果驗證失敗就拋出一個錯誤，否則就返回這個字段值
    # def clean_username(self):
    #     usernname = self.cleaned_data.get("username")
    #     return username
